import { defineComponent, onMounted, onUnmounted, ref } from 'vue'
import './ParticleBackground.css'

interface Particle {
  x: number
  y: number
  vx: number
  vy: number
  size: number
  opacity: number
}

export default defineComponent({
  name: 'ParticleBackground',
  setup() {
    const canvasRef = ref<HTMLCanvasElement>()
    let animationId: number
    let particles: Particle[] = []

    const createParticles = (count: number) => {
      particles = []
      for (let i = 0; i < count; i++) {
        particles.push({
          x: Math.random() * window.innerWidth,
          y: Math.random() * window.innerHeight,
          vx: (Math.random() - 0.5) * 0.5,
          vy: (Math.random() - 0.5) * 0.5,
          size: Math.random() * 2 + 1,
          opacity: Math.random() * 0.5 + 0.2
        })
      }
    }

    const drawParticles = (ctx: CanvasRenderingContext2D) => {
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height)

      // 绘制粒子
      particles.forEach(particle => {
        ctx.beginPath()
        ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2)
        ctx.fillStyle = `rgba(0, 212, 255, ${particle.opacity})`
        ctx.fill()

        // 更新位置
        particle.x += particle.vx
        particle.y += particle.vy

        // 边界检测
        if (particle.x < 0 || particle.x > ctx.canvas.width) particle.vx *= -1
        if (particle.y < 0 || particle.y > ctx.canvas.height) particle.vy *= -1
      })

      // 绘制连线
      particles.forEach((p1, i) => {
        particles.slice(i + 1).forEach(p2 => {
          const dx = p1.x - p2.x
          const dy = p1.y - p2.y
          const distance = Math.sqrt(dx * dx + dy * dy)

          if (distance < 150) {
            ctx.beginPath()
            ctx.strokeStyle = `rgba(0, 212, 255, ${(1 - distance / 150) * 0.2})`
            ctx.lineWidth = 0.5
            ctx.moveTo(p1.x, p1.y)
            ctx.lineTo(p2.x, p2.y)
            ctx.stroke()
          }
        })
      })
    }

    const animate = () => {
      const canvas = canvasRef.value
      if (!canvas) return

      const ctx = canvas.getContext('2d')
      if (!ctx) return

      drawParticles(ctx)
      animationId = requestAnimationFrame(animate)
    }

    const resizeCanvas = () => {
      const canvas = canvasRef.value
      if (!canvas) return

      canvas.width = window.innerWidth
      canvas.height = window.innerHeight
      createParticles(80)
    }

    onMounted(() => {
      resizeCanvas()
      animate()
      window.addEventListener('resize', resizeCanvas)
    })

    onUnmounted(() => {
      cancelAnimationFrame(animationId)
      window.removeEventListener('resize', resizeCanvas)
    })

    return () => (
      <canvas
        ref={canvasRef}
        class="particle-background"
      />
    )
  }
})
